package com.example.yangxu0703.thundermapclient.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.media.midi.MidiDevice;
import android.net.wifi.WifiConfiguration;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yangxu0703.thundermapclient.R;
import com.example.yangxu0703.thundermapclient.adapter.PagerFragmnetAdapter;
import com.example.yangxu0703.thundermapclient.callback.Progressback;
import com.example.yangxu0703.thundermapclient.fragment.PictureFragment;
import com.example.yangxu0703.thundermapclient.fragment.VedioFragment;
import com.example.yangxu0703.thundermapclient.interaction.HoldByDialog;
import com.thundersoft.mm.phone.ConnectionManager;
import com.thundersoft.mm.phone.Wifi.WifiP2pSocket;
import com.thundersoft.mm.phone.bt.BtTextServerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Currency;
import java.util.Timer;
import java.util.TimerTask;

import static android.view.Gravity.BOTTOM;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class MediaCenterActivity extends BaseActivity implements View.OnClickListener {

    private TextView back_main, pic_tag, pic_point, vedio_tag, vedio_point, choose_item;
    private ViewPager pager;
    private int current_fragment;
    private ArrayList<Fragment> all_fragment;
    private Button res_down;
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private Dialog dialog;
    private TextView nameview, title_people;
    private ProgressBar progress;
    private boolean Mode = false;
    private PopupWindow window;
    private View Contentview;
    private HoldByDialog holdByDialog;
    private boolean isfirst = true;
    public  PagerFragmnetAdapter pagerAdapter ;
    public  static Timer checkBluetooth=null;
    private boolean gotoConnectBlue=false;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //holdByDialog.changeMessage("正在传输...");
                    break;
                case 1:
                    Toast.makeText(MediaCenterActivity.this, "蓝牙未连接！", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    //if (current_fragment == 0) {
                        ((PictureFragment) all_fragment.get(0)).notifydata(2,"downLoad_update");
                    //} else {
                        ((VedioFragment) all_fragment.get(1)).notifydata();
                    //}
                    holdByDialog.dismiss();
                    break;
                case 3:
                    title_people.setVisibility(View.GONE);
                    break;
                case 4:
                    res_down.setVisibility(View.VISIBLE);
                    break;

                case 5:
                    holdByDialog = new HoldByDialog(MediaCenterActivity.this);
                    holdByDialog.showDialog("正在传输");
                    break;
                case 6:
                    holdByDialog.dismiss();
                    Toast.makeText(MediaCenterActivity.this, "已同步到最新！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Contentview = LayoutInflater.from(this).inflate(R.layout.activity_media_center, null, false);
        setContentView(Contentview);
        initview();
        all_fragment = new ArrayList<>();
        all_fragment.add(new PictureFragment());
        all_fragment.add(new VedioFragment());
        pagerAdapter = new PagerFragmnetAdapter(getSupportFragmentManager(), all_fragment);
        pager.setAdapter(pagerAdapter);
        pager.setCurrentItem(0);
        initViewPager();
       /* manager = getSupportFragmentManager();
        fragments = new Fragment[2];
        fragments[0] = manager.findFragmentById(R.id.picture_fragment);
        fragments[1] = manager.findFragmentById(R.id.vedio_fragment);
        transaction = manager.beginTransaction();
        transaction.hide(fragments[0]).hide(fragments[1]).show(fragments[0]).commit();*/
        Log.i("order", "onCreate()" + "--------");
        //((PictureFragment) fragments[0]).update();
        setcolor(0);
        current_fragment = 0;
        //initDialog();
    }
    private void initViewPager() {
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                setcolor(position);
                //更新数据
            }

            @Override
            public void onPageSelected(int position) {
                current_fragment=position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        ReconnectBT();
    }

    public static void ReconnectBT() {
        if(ConnectionManager.btTextMsgListener.connected){
            Log.i("Reconnect BT","p2p");
            if (ConnectionManager.mGlassesIp==null){
                final Timer p2p=new Timer();
                p2p.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        ConnectionManager.wifiConnection.init(ConnectionManager.mContext);
                        if (ConnectionManager.mGlassesIp!=null){
                            p2p.cancel();
                            p2p.purge();
                        }
                    }
                },0,2000);

            }
        }else {
              Log.i("Reconnect BT","p2p");
            checkBluetooth=new Timer();
            checkBluetooth.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (!ConnectionManager.btTextMsgListener.connected){
                         ConnectionManager.wifiConnection.init(ConnectionManager.mContext);
                    }else {
                        checkBluetooth.cancel();
                        checkBluetooth.purge();
                        checkBluetooth=null;
                    }

                }
            },0,1000);
        }
    }

    /*private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_reciver_layout, null, false);
        nameview = view.findViewById(R.id.filename);
        progress = view.findViewById(R.id.current_position);
        title_people = view.findViewById(R.id.title_people);
        //nameview.setVisibility(View.GONE);
        //progress.setVisibility(View.GONE);
        builder.setView(view);
        dialog = builder.create();
    }*/

    private void initview() {
        pager = findViewById(R.id.content_media);
        back_main = findViewById(R.id.back_main);
        back_main.setOnClickListener(this);
        pic_tag = findViewById(R.id.pic_tag);
        pic_tag.setOnClickListener(this);
        pic_point = findViewById(R.id.pic_point);
        vedio_tag = findViewById(R.id.vedio_tag);
        vedio_tag.setOnClickListener(this);
        vedio_point = findViewById(R.id.vedio_point);
        choose_item = findViewById(R.id.choose_item);
        choose_item.setOnClickListener(this);
        res_down = findViewById(R.id.start_download);
        res_down.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_main:
                MediaCenterActivity.this.finish();
                break;
            case R.id.choose_item:
                if(!Mode) {
                    Log.i("MODE",Mode+"------"+current_fragment);
                    res_down.setVisibility(View.GONE);
                    Mode = true;
                    if (current_fragment == 0) {
                        ((PictureFragment) all_fragment.get(0)).setChooseMode(Mode);
                    } else {
                        ((VedioFragment) all_fragment.get(1)).setChooseMode(Mode);
                    }
                    showpopuwindow();
                }else {
                    Log.i("MODE",Mode+"------");
                    res_down.setVisibility(View.VISIBLE);
                    Mode = false;
                    if (current_fragment == 0) {
                        ((PictureFragment) all_fragment.get(0)).setChooseMode(Mode);
                    } else {
                        ((VedioFragment) all_fragment.get(1)).setChooseMode(Mode);
                    }
                    dismisspopuwindow();
                }
                break;
            case R.id.start_download:
                //下载数据
                if (ConnectionManager.btTextMsgListener.connected){
                    if (ConnectionManager.mGlassesIp!=null) {
                        handler.sendEmptyMessage(5);
                        JSONObject o = new JSONObject();
                        try {
                            o.put("type", String.valueOf(4));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        ConnectionManager.btTextMsgListener.sendMsg(o.toString().getBytes());
                        ConnectionManager.btTextMsgListener.setPicCallback(new BtTextServerListener.PicCallback() {
                            @Override
                            public void isLastPic(String type) {
                                Log.i("TAG", "btTextMsgListener" + type);
                                if (type.equals("11")) {
                                    handler.sendEmptyMessageDelayed(2, 2000);
                                } else if (type.equals("10")) {
                                    handler.sendEmptyMessage(6);
                                } else {
                                    handler.sendEmptyMessage(1);
                                }
                            }
                        });
                    }else {
                        ConnectionManager.wifiConnection.init(ConnectionManager.mContext);
                        Toast.makeText(MediaCenterActivity.this,"WIFIp2p正在连接请稍后！",Toast.LENGTH_SHORT).show();
                    }
                }else {
                    ReconnectBT();
                    Toast.makeText(MediaCenterActivity.this,"蓝牙正在连接请稍后！",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.pic_tag:
                /*transaction = manager.beginTransaction();
                transaction.hide(fragments[0]).hide(fragments[1]).show(fragments[0]).commit();
                setcolor(0);
                ((PictureFragment) fragments[0]).update();
                current_fragment = 0;*/
                pager.setCurrentItem(0);
                current_fragment = 0;
                break;
            case R.id.vedio_tag:
               /* transaction = manager.beginTransaction();
                transaction.hide(fragments[0]).hide(fragments[1]).show(fragments[1]).commit();
                setcolor(1);
                ((VedioFragment) fragments[1]).update();
                current_fragment = 1;*/
                pager.setCurrentItem(1);
                current_fragment = 1;
                break;
        }
    }

    private void showpopuwindow() {
        choose_item.setText("取消");
        View view = View.inflate(this, R.layout.popu_pic_operation, null);
        Button share = view.findViewById(R.id.share_pic);
        Button delete = view.findViewById(R.id.delete_pic);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享操作
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除操作
                Mode=false;
                Log.i("TAG", "" + current_fragment);
                if (current_fragment == 0) {
                    ((PictureFragment) all_fragment.get(0)).deletefile();
                    ((PictureFragment) all_fragment.get(0)).setChooseMode(Mode);
                } else {
                    ((VedioFragment)all_fragment.get(1)).deletefile();
                   ((VedioFragment)all_fragment.get(1)).setChooseMode(Mode);
                }
                res_down.setVisibility(View.VISIBLE);
               dismisspopuwindow();
            }
        });
        window = new PopupWindow(this);
        window.setContentView(view);
        window.setHeight(WRAP_CONTENT);
        window.setWidth(WRAP_CONTENT);
        window.showAtLocation(Contentview, BOTTOM, 0, 0);
    }

    private void dismisspopuwindow() {
        choose_item.setText("选择");
        if (window != null) {
            window.dismiss();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onBackPressed() {
        // super.onBackPressed();
        if (Mode) {
            if (current_fragment == 0) {
                ((PictureFragment) all_fragment.get(0)).setChooseMode(false);

            } else {
                ((VedioFragment) all_fragment.get(1)).setChooseMode(false);

            }
            Mode = false;
            handler.sendEmptyMessage(4);
            dismisspopuwindow();
        } else {
            super.onBackPressed();
        }
        ConnectionManager.stopWifiP2p();
        ConnectionManager.wifiConnection.release();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ConnectionManager.stopWifiP2p();
        ConnectionManager.wifiConnection.release();
    }

    public void setcolor(int i) {
        if (i == 0) {
            pic_point.setBackgroundColor(getResources().getColor(R.color.blue));
            vedio_point.setBackgroundColor(getResources().getColor(R.color.grey));
        } else {
            pic_point.setBackgroundColor(getResources().getColor(R.color.grey));
            vedio_point.setBackgroundColor(getResources().getColor(R.color.blue));
        }
    }


}
